package com.hulizuofang.wol.chat.server.channel;

import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.gwt.dev.json.JsonObject;
import com.google.inject.Inject;
import com.hulizuofang.wol.chat.client.data.ChatUser;
import com.hulizuofang.wol.chat.client.message.ParserChannelMessageHandler;
import com.hulizuofang.wol.chat.client.message.ParserChannelMessageHandler.MessageType;

public class ChannelProvider {
	private static final Logger logger = Logger.getLogger(ChannelProvider.class.getName());

	private final ChannelService channelService;

	@Inject
	public ChannelProvider(ChannelService channelService) {
		this.channelService = channelService;
	}

	public String getToken(ChatUser user) {
		String token = channelService.createChannel(user.getId());
		return token;
	}

	public void tellIsOnline(ChatUser sender, ChatUser recipient) {
		JsonObject jsonObject = new JsonObject();
		jsonObject.put(ParserChannelMessageHandler.TYPE, MessageType.UpdateOnlineUser.name());
		jsonObject.put("login", sender.getLogin());
		jsonObject.put("id", sender.getId());
		
		StringWriter writer = new StringWriter();
		try {
			jsonObject.write(writer);
		} catch (IOException e) {
			throw new IllegalStateException("While building JSON message",e);
		}
		
		String json = writer.toString();

		if (logger.isLoggable(Level.INFO)) {
			logger.info(String.format("send from %s to %s message: %s", sender, recipient, json));
		}
		channelService.sendMessage(new ChannelMessage(recipient.getId(), json));
	}

	public boolean sendChat(ChatUser sender, ChatUser recipient, String message) {
		JsonObject jsonObject = new JsonObject();
		jsonObject.put(ParserChannelMessageHandler.TYPE, MessageType.Chat.name());
		jsonObject.put("sender", sender.getId());
		jsonObject.put("message", message);

		StringWriter writer = new StringWriter();
		try {
			jsonObject.write(writer);
		} catch (IOException e) {
			throw new IllegalStateException("While building JSON message",e);
		}
		
		String json = writer.toString();
		if (logger.isLoggable(Level.INFO)) {
			logger.info(String.format("send from %s to %s message: %s", sender, recipient, json));
		}
		channelService.sendMessage(new ChannelMessage(recipient.getId(), json));
		return true;
	}

}
